import 'package:flutter/material.dart';
import 'package:jd_shopping/services/ScreenAdaper.dart';
import 'package:jd_shopping/pages/Coustom/JdButton.dart';
import 'package:jd_shopping/Model/ProductDetaileModel.dart';
import 'package:jd_shopping/HttpRequest/configDomain.dart';
import 'package:jd_shopping/pages/Tools/EventBus.dart';
import 'package:jd_shopping/pages/ProductDetaileTabBarView/CartDetaileNumber.dart';
import 'package:jd_shopping/pages/services/CartServices.dart';
import 'package:jd_shopping/pages/Providers/CartShow.dart';
import 'package:provider/provider.dart';
import 'package:fluttertoast/fluttertoast.dart';

class ProductTabBarView extends StatefulWidget {
  final ProductDetaileItemModel productDetaileItemModel;
  ProductTabBarView({Key key, this.productDetaileItemModel});

  @override
  _ProductTabBarViewState createState() => _ProductTabBarViewState();
}

class _ProductTabBarViewState extends State<ProductTabBarView>
    with AutomaticKeepAliveClientMixin {
  @override
  bool get wantKeepAlive => true;
  List _attr = [];
  String _selectedValue = '';
  var actionEventBus;
  ProductDetaileItemModel _productDetaileItemModel;
  var cartProvider;

  @override
  void initState() {
    // Future.delayed(Duration(milliseconds: 500), (){
    this._attr = widget.productDetaileItemModel.attr;
    this._productDetaileItemModel = widget.productDetaileItemModel;
    _initAttr();
    //  });

    //监听广播
    actionEventBus = eventBus.on<ProductContentEvent>().listen((event) {
      print(event);
      this._attrBottomSheet();
    });
    super.initState();
  }

  //销毁
  void dispose() {
    super.dispose();
    this.actionEventBus.cancel(); //取消事件监听
  }

  //初始化Attr 格式化数据
  _initAttr() {
    var attr = this._attr;
    for (var i = 0; i < attr.length; i++) {
      for (var j = 0; j < attr[i].list.length; j++) {
        if (j == 0) {
          attr[i].attrList.add({"title": attr[i].list[j], "checked": true});
        } else {
          attr[i].attrList.add({"title": attr[i].list[j], "checked": false});
        }
      }
    }
    print(attr[0].attrList);
    print(attr[0].cate);
    print(attr[0].list);
    _getSelectedAttrValue();
  }

  //获取选中的值
  _getSelectedAttrValue() {
    var _list = this._attr;
    List tempArr = [];
    for (var i = 0; i < _list.length; i++) {
      for (var j = 0; j < _list[i].attrList.length; j++) {
        if (_list[i].attrList[j]['checked'] == true) {
          tempArr.add(_list[i].attrList[j]["title"]);
        }
      }
    }
    setState(() {
      this._selectedValue = tempArr.join(',');
      widget.productDetaileItemModel.selectedAttr = this._selectedValue;
    });
  }

  //改变属性值
  _changeAttr(cate, title, setBottomState) {
    var attr = this._attr;
    for (var i = 0; i < attr.length; i++) {
      if (attr[i].cate == cate) {
        for (var j = 0; j < attr[i].attrList.length; j++) {
          attr[i].attrList[j]["checked"] = false;
          if (title == attr[i].attrList[j]["title"]) {
            attr[i].attrList[j]["checked"] = true;
          }
        }
      }
    }
    setBottomState(() {
      //注意  改变showModalBottomSheet里面的数据 来源于StatefulBuilder
      this._attr = attr;
    });
    _getSelectedAttrValue();
  }

  List<Widget> _getAttrItemWidget(attrItem, setBottomState) {
    List<Widget> attrItemList = [];
    attrItem.attrList.forEach((item) {
      attrItemList.add(Container(
          margin: EdgeInsets.all(10),
          child: InkWell(
            onTap: () {
              _changeAttr(attrItem.cate, item["title"], setBottomState);
            },
            child: Chip(
              label: Text("${item['title']}"),
              padding: EdgeInsets.all(10),
              backgroundColor: item["checked"] ? Colors.red : Colors.black26,
            ),
          )));
    });
    return attrItemList;
  }

  //封装一个组件 渲染attr
  List<Widget> _getAttrWidget(setBottomState) {
    print(widget.productDetaileItemModel.attr);
    List<Widget> attrList = [];
    widget.productDetaileItemModel.attr.forEach((attrItem) {
      attrList.add(Wrap(
        children: <Widget>[
          Container(
            width: ScreenAdaper.width(110),
            child: Padding(
              padding: EdgeInsets.only(top: ScreenAdaper.height(32)),
              child: Text("${attrItem.cate}: ",
                  style: TextStyle(fontWeight: FontWeight.bold),
                  textAlign: TextAlign.left),
            ),
          ),
          Container(
            width: ScreenAdaper.getScreenWidth() - 110,
            child: Wrap(
              children: _getAttrItemWidget(attrItem, setBottomState),
            ),
          )
        ],
      ));
    });
    return attrList;
  }

  _attrBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (context) {
          return StatefulBuilder(
              builder: (BuildContext context, setBottomState) {
            return GestureDetector(
              onTap: () {
                return false;
              },
              child: Stack(
                children: <Widget>[
                  Container(
                    padding: EdgeInsets.all(ScreenAdaper.height(35)),
                    child: ListView(
                      children: <Widget>[
                        Column(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: _getAttrWidget(setBottomState),
                        ),
                        Divider(),
                        Container(
                          child: Row(
                            children: <Widget>[
                              Text("数量: ",
                                  style:
                                      TextStyle(fontWeight: FontWeight.bold)),
                              SizedBox(width: 10),
                              CartNum(_productDetaileItemModel)
                            ],
                          ),
                        ),
                      ],
                    ),
                  ),
                  Positioned(
                    width: ScreenAdaper.getScreenWidth(),
                    height: ScreenAdaper.height(134),
                    bottom: 0,
                    child: Container(
                      child: Row(
                        children: <Widget>[
                          Expanded(
                            flex: 1,
                            child: JdButton(
                              color: Color.fromRGBO(253, 1, 0, 0.9),
                              text: "加入购物车",
                              cb: () async {
                                await CartServices.addCart(
                                    widget.productDetaileItemModel);
                                Navigator.of(context).pop();
                                this.cartProvider.updateCartList();
                                print('加入购物车');
                                Fluttertoast.showToast(
                                    msg: "加入购物车成功",
                                    toastLength: Toast.LENGTH_SHORT,
                                    gravity: ToastGravity.CENTER,
                                    timeInSecForIosWeb: 1);
                              },
                            ),
                          ),
                          Expanded(
                            flex: 1,
                            child: JdButton(
                              color: Color.fromRGBO(255, 165, 0, 0.9),
                              text: "立即购买",
                              cb: () {
                                print('立即购买');
                              },
                            ),
                          )
                        ],
                      ),
                    ),
                  )
                ],
              ),
            );
          });
        });
  }

  @override
  Widget build(BuildContext context) {
    this.cartProvider = Provider.of<CartsShow>(context);
    ScreenAdaper.init(context);
    String pic = widget.productDetaileItemModel != null
        ? widget.productDetaileItemModel.pic
        : '';
    pic = ConfigDomian.domain + '/' + pic.replaceAll('\\', '/');
    return ListView(
        padding: EdgeInsets.only(bottom: ScreenAdaper.height(134)),
        children: [
          widget.productDetaileItemModel != null
              ? Container(
                  padding: EdgeInsets.all(ScreenAdaper.width(10)),
                  child: Column(
                    children: <Widget>[
                      Container(
                        width: double.infinity,
                        child: AspectRatio(
                          //防止服务器返回的图片大小不一致导致高度不一致问题
                          aspectRatio: 450 / 441,
                          child: Image.network(
                            pic,
                            fit: BoxFit.cover,
                          ),
                        ),
                      ),
                      //标题
                      Container(
                        alignment: Alignment.centerLeft,
                        padding: EdgeInsets.only(top: 10),
                        child: Text(
                          widget.productDetaileItemModel.title,
                          style: TextStyle(
                              color: Colors.black87,
                              fontSize: ScreenAdaper.size(36)),
                          textAlign: TextAlign.left,
                        ),
                      ),
                      Container(
                          padding: EdgeInsets.only(top: 10),
                          child: Text(
                            widget.productDetaileItemModel.subTitle,
                            style: TextStyle(
                                color: Colors.black54,
                                fontSize: ScreenAdaper.size(28)),
                            textAlign: TextAlign.left,
                          )),

                      //价格
                      Container(
                        padding: EdgeInsets.only(top: 10),
                        child: Row(
                          children: <Widget>[
                            Expanded(
                              flex: 1,
                              child: Row(
                                children: <Widget>[
                                  Text("特价: "),
                                  Text(widget.productDetaileItemModel.oldPrice,
                                      style: TextStyle(
                                          color: Colors.red,
                                          fontSize: ScreenAdaper.size(46))),
                                ],
                              ),
                            ),
                            Expanded(
                              flex: 1,
                              child: Row(
                                mainAxisAlignment: MainAxisAlignment.end,
                                children: <Widget>[
                                  Text("原价: "),
                                  Text(widget.productDetaileItemModel.price,
                                      style: TextStyle(
                                          color: Colors.black38,
                                          fontSize: ScreenAdaper.size(28),
                                          decoration:
                                              TextDecoration.lineThrough)),
                                ],
                              ),
                            )
                          ],
                        ),
                      ),
                      //筛选
                      Container(
                          margin: EdgeInsets.only(top: 10),
                          height: ScreenAdaper.height(80),
                          child: InkWell(
                            child: Row(
                              children: <Widget>[
                                Text("已选: ",
                                    style:
                                        TextStyle(fontWeight: FontWeight.bold)),
                                Text(this._selectedValue)
                              ],
                            ),
                            onTap: () {
                              _attrBottomSheet();
                            },
                          )),
                      Divider(),
                      Container(
                        height: ScreenAdaper.height(80),
                        child: Row(
                          children: <Widget>[
                            Text("运费: ",
                                style: TextStyle(fontWeight: FontWeight.bold)),
                            Text("免运费")
                          ],
                        ),
                      ),
                      Divider(),
                    ],
                  ),
                )
              : Text('load.....')
        ]);
  }
}
